package com.scau402.common.utils.code;


import com.scau402.common.utils.CustomRedisConfig;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class TenantCodeUtils {

    private static final String KEY_NAME = "TENANT_KEY";

    public void setCurrentCodeToMax(String maxCode) {
        CustomRedisConfig cc = new CustomRedisConfig();
        RedisURI redisUri = RedisURI.Builder.redis(cc.REDIS_HOST, cc.REDIS_PORT).withPassword(cc.AUTH).withDatabase(1).build();
        RedisClient client = RedisClient.create(redisUri);

        // 创建StatefulRedisConnection对象
        StatefulRedisConnection<String, String> connection = client.connect();

        // 获取同步的RedisCommands对象
        RedisCommands<String, String> commands = connection.sync();

        // 执行Redis命令
        commands.set(KEY_NAME, maxCode);

        // 关闭连接
        connection.close();
        client.shutdown();
    }

    public synchronized static String getNewCode() throws InterruptedException {
        CustomRedisConfig cc = new CustomRedisConfig();
        RedisURI redisUri = RedisURI.Builder.redis(cc.REDIS_HOST, cc.REDIS_PORT).withPassword(cc.AUTH).withDatabase(1).build();
        RedisClient client = RedisClient.create(redisUri);

        // 创建StatefulRedisConnection对象
        StatefulRedisConnection<String, String> connection = client.connect();

        // 获取同步的RedisCommands对象
        RedisCommands<String, String> commands = connection.sync();

        Long id = commands.incr(KEY_NAME);

        // 关闭连接
        connection.close();
        client.shutdown();

        String formattedNumber = String.format("%06d", id); // 补全ID数字到6位
        String tenantCode = "T" + formattedNumber;
        return tenantCode;
    }

}
